<!--
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2024-09-09 09:53:25
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2024-09-10 09:17:59
 * @FilePath: \hy-ui\src\views\taskMassage\components\project\components\file.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="file">
    <div class="fileHeader">
      <div class="navBar">
        <el-breadcrumb>
          <span
            v-for="(item, index) in breList"
            @click="handlegetData(index, item)"
            :key="index"
            ><el-breadcrumb-item
              :class="[breList.length === index + 1 ? 'isColor' : null]"
              >{{ index === 0 ? "项目首页" : item && item.name
              }}<i
                class="el-icon-arrow-right"
                v-show="breList.length > index + 1"
              ></i></el-breadcrumb-item
          ></span>
        </el-breadcrumb>
      </div>

      <div style="display: flex; align-items: center">
        <el-input
          size="mini"
          placeholder="请输入名称"
          prefix-icon="el-icon-search"
          v-model="searchValue"
          style="width: 300px"
          clearable
          @keydown.enter.native="getList"
        >
        </el-input>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addFile('add')"
          style="margin-left: 12px"
          v-if="isTaskFolder === '0'"
          >创建文件夹</el-button
        >
        <el-upload
          class="upload-demo"
          :action="uploadImgUrl"
          :headers="headers"
          :show-file-list="false"
          :on-success="uploadSuccess"
        >
          <el-button
            type="primary"
            icon="el-icon-upload"
            size="mini"
            style="margin-left: 12px"
            v-if="isTaskFolder === '0'"
            >上传文件</el-button
          >
        </el-upload>
      </div>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%; padding: 0 12px"
        height="62vh"
        v-loading="loading"
        highlight-current-row
        @current-change="handleCurrentChange"
      >
        <el-table-column
          prop="name"
          label="名称"
          width="350"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="taskTitle"
          label="所属任务"
          width="350"
          show-overflow-tooltip
          v-if="isTaskFolder === '1'"
        >
        </el-table-column>
        <el-table-column
          prop="format"
          label="文件格式"
          width="350"
          show-overflow-tooltip
          :formatter="(row) => getFileType(row.format)"
          v-if="isTaskFolder === '1'"
        >
        </el-table-column>
        <el-table-column
          prop="size"
          label="大小"
          :formatter="
            (row) => (row.size ? formatBytes(Number(row.size)) : '--')
          "
        >
        </el-table-column>
        <el-table-column
          prop="uploadByName"
          :label="isTaskFolder === '1' ? '上传人' : '创建人'"
        >
        </el-table-column>
        <el-table-column
          prop="uploadTime"
          :label="isTaskFolder === '1' ? '上传时间' : '更新时间'"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click.stop="handleTaskDetail(scope.row)"
              v-if="isTaskFolder === '1'"
              >任务详情</el-button
            >
            <el-button
              type="text"
              v-if="
                isTaskFolder === '0' &&
                !scope.row.url &&
                scope.row.taskFlag === '0'
              "
              icon="el-icon-edit"
              @click.stop="() => addFile('edit', scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              v-if="
                isTaskFolder === '0' &&
                scope.row.url &&
                scope.row.taskFlag === '0'
              "
              icon="el-icon-edit"
              @click.stop="() => addFile('move', scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              v-if="isTaskFolder === '0' && scope.row.taskFlag === '0'"
              style="color: #f56c6c"
              icon="el-icon-delete"
              @click.stop="deleteFileOrFolder(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="display: flex; justify-content: center">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      title="文件夹"
      :visible.sync="listOpen"
      v-if="listOpen"
      width="30%"
      :before-close="() => (listOpen = false)"
    >
      <el-form
        :model="createForm"
        :rules="rules"
        ref="createFormRef"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="文件夹名称" prop="name">
          <el-input
            v-model="createForm.name"
            placeholder="请输入文件夹名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="所属文件夹"
          :prop="folderType === 'add' ? null : 'parentId'"
          v-if="folderType !== 'add'"
        >
          <treeselect
            v-model="createForm.parentId"
            :searchable="true"
            :options="options"
            :show-count="true"
            noOptionsText="暂无数据"
            placeholder="请选择所属文件夹"
            :normalizer="normalizer"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => (listOpen = false)">取 消</el-button>
        <el-button type="primary" @click="createListSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <taskDrawer
      ref="taskDrawer"
      v-if="visibleDrawer"
      :visible="visibleDrawer"
      :close="taskDrawerClose"
      :propsObj="taskObjProps"
      :isFile="true"
    />
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  fileList,
  fileCreate,
  deleteFile,
  fileTree,
  updateFile,
} from "@/api/task/project.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import fileTypeObj from "@/views/taskMassage/components/project/components/fileType.js";
import { getTaskDetail } from "@/api/task/task.js";
import taskDrawer from "@/views/taskMassage/components/task/components/taskDrawer.vue";
export default {
  components: { Treeselect, taskDrawer },
  props: {
    row: {
      type: Object,
      default: () => {
        {
        }
      },
    },
  },
  data() {
    return {
      loading: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/oss/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      searchValue: "",
      tableData: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      breList: [],
      listOpen: false,
      createForm: {},
      rules: {
        name: [
          { required: true, message: "请输入文件夹名称", trigger: "blur" },
        ],
        parentId: [
          { required: true, message: "请选择所属文件夹", trigger: "change" },
        ],
      },
      options: [],
      folderType: undefined,
      isTaskFolder: "0",
      visibleDrawer: false,
      currentId: undefined,
    };
  },
  mounted() {
    this.reset();
  },
  methods: {
    reset() {
      this.breList = [this.row];
      this.getList();
    },
    normalizer(node) {
      if (node?.children && !node?.children?.length) {
        delete node.children;
      }

      return {
        id: node["id"],
        label: node["name"],
        children: node.children,
        isDisabled: node["id"] === this.currentId ? true : false,
      };
    },
    async deleteFileOrFolder(row) {
      this.$confirm(`确认删除该${row.url ? "文件" : "文件夹"}吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteFile(row.id);
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          }
        })
        .catch(() => {});
    },
    async handleTaskDetail(row) {
      const res = await getTaskDetail(row.taskId);
      this.taskObjProps = {
        type: res.data.type === "1" ? "standard" : "flow",
        getList: this.getList,
        taskDetailData: res.data,
        checkData: false,
      };
      this.visibleDrawer = true;
    },
    taskDrawerClose() {
      this.$confirm("确认关闭操作吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.visibleDrawer = false;
        })
        .catch(() => {});
    },
    getFileType(val) {
      if (fileTypeObj[val]) {
        return fileTypeObj[val];
      }
      return val;
    },
    handlegetData(index, item) {
      this.isTaskFolder = "0";
      this.searchValue = undefined;
      if (index === 0) {
        this.breList = [item];
      } else {
        this.breList = this.breList.slice(0, index + 1);
      }
      this.queryParams = {
        ...this.queryParams,
        pageNum: 1,
        pageSize: 10,
      };
      this.getList();
    },
    handleCurrentChange(row) {
      if (row?.url) {
        const file = row;
        if (file.url?.includes(".docx")) {
          window.open(`/fileView?type=word&url=${file.url}&name=${file.name}`);
        } else if (file.url?.includes(".xls") || file.url?.includes(".xlsx")) {
          window.open(`/fileView?type=excel&url=${file.url}&name=${file.name}`);
        } else if (file.url?.includes(".pdf")) {
          window.open(`/fileView?type=pdf&url=${file.url}&name=${file.name}`);
        } else if (
          file.url.includes(".png") ||
          file.url.includes(".gif") ||
          file.url.includes(".jpg") ||
          file.url.includes(".jepg")
        ) {
          window.open(`/fileView?type=img&url=${file.url}&name=${file.name}`);
        } else {
          window.open(`/fileView?type=no&url=${file.url}&name=${file.name}`);
        }
      } else {
        this.searchValue = undefined;
        this.isTaskFolder = row.taskFlag;
        this.breList.push(row);
        this.queryParams = {
          ...this.queryParams,
          pageNum: 1,
          pageSize: 10,
        };
        this.getList();
      }
    },
    async addFile(type, row) {
      this.folderType = type;
      this.createForm = {};
      if (type === "edit" || type === "move") {
        const res = await fileTree(row.projectId, {
          type: type === "edit" ? "1" : "1",
          taskFlag: "0",
        });
        this.createForm = {
          name: row.name,
          parentId: row.parentId,
          id: row.id,
        };
        this.options = [{ id: 0, name: "根目录", children: res.data }];
        this.currentId = row.id;
      }

      this.listOpen = true;
    },
    async uploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        const params = {
          projectId: this.breList[0]?.id,
          name: response.data?.fileName,
          url: response.data?.url,
          format: file.raw?.type,
          size: file.raw?.size,
          type: "2",
          parentId:
            this.breList.length <= 1 ? undefined : this.breList.at(-1)?.id,
        };
        const res = await fileCreate(params);
        if (res.code === 200) {
          this.$message.success("上传成功");
          this.getList();
        }
      } else {
        this.$$message.error(res.msg);
      }
    },
    async getList() {
      this.loading = true;
      this.tableData = [];
      const res = await fileList(this.row.id, {
        ...this.queryParams,
        // type: this.breList.at(-1).type,
        id: this.breList.length <= 1 ? undefined : this.breList.at(-1)?.id,
        name: this.searchValue,
      });
      this.tableData = res.rows;
      this.total = res.total;
      this.loading = false;
    },
    createListSubmit() {
      this.$refs["createFormRef"].validate(async (valid) => {
        if (valid) {
          let res = undefined;
          if (this.folderType === "add") {
            res = await fileCreate({
              parentId:
                this.breList.length <= 1 ? undefined : this.breList.at(-1)?.id,
              projectId: this.breList[0]?.id,
              type: "1",
              name: this.createForm.name,
            });
          } else {
            res = await updateFile({
              ...this.createForm,
              parentId:
                this.createForm.parentId === 0 ||
                this.createForm.parentId === "0"
                  ? undefined
                  : this.createForm.parentId,
            });
          }
          if (res.code === 200) {
            this.$message.success(
              `${this.folderType === "add" ? "创建成功" : "修改成功"}`
            );
            this.listOpen = false;
            this.getList();
          }
        }
      });
    },
    formatBytes(bytes, decimals = 2) {
      if (bytes === 0) return "0";
      const k = 1024;
      const dm = decimals < 0 ? 0 : decimals;
      const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
    },
  },
};
</script>

<style lang="scss" scoped>
.file {
  .isColor {
    ::v-deep .el-breadcrumb__inner {
      color: #1890ff !important;
      font-weight: bold !important;
      font-size: 13px;
    }
  }
  .navBar {
    display: flex;
    align-items: center;
    ::v-deep .el-breadcrumb__inner {
      cursor: pointer;
      font-size: 13px;
      color: #333;
      .el-icon-arrow-right {
        padding: 0 3px;
      }
    }
  }
  .fileHeader {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px 12px;
    ::v-deep .el-input__prefix {
      height: 28px;
    }
  }
  ::v-deep .pagination-container {
    width: 100%;
    margin: 0;
    height: 52px;
    .el-pagination {
      right: 50%;
      transform: translateX(50%);
    }
  }
}
</style>